package com.tduck.cloud.security.service;

import cn.hutool.core.bean.BeanUtil;
import com.tduck.cloud.common.entity.security.LoginUserEntity;
import com.tduck.cloud.common.entity.security.SysUserVO;
import com.tduck.cloud.common.exception.BaseException;
import com.tduck.cloud.system.entity.SysUserEntity;
import com.tduck.cloud.system.exception.UserPasswordNotMatchException;
import com.tduck.cloud.system.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 登录校验方法
 *
 * @author tduck
 */
@Component
@RequiredArgsConstructor
public class SysLoginService {
    private final TokenService tokenService;

    private final AuthenticationManager authenticationManager;


    private final SysUserService userService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password) {
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new UserPasswordNotMatchException("用户不存在/密码错误");
            } else {
                throw new BaseException(e.getMessage());
            }
        }
        LoginUserEntity loginUser = (LoginUserEntity) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUser());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 记录登录信息
     */
    public void recordLoginInfo(SysUserVO user) {
        user.setLoginDate(LocalDateTime.now());
        SysUserEntity sysUserEntity = BeanUtil.toBean(user, SysUserEntity.class);
        userService.updateById(sysUserEntity);
    }
}
